package com.hfjyz.base.interceptor;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.hfjyz.base.bean.MenuBean;
import com.hfjyz.base.constant.BaseConstant;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginInterceptor extends AbstractInterceptor {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 7320483809396043091L;

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        invocation.getAction();
        HttpSession session = ServletActionContext.getRequest().getSession();
        if (!isLogin(session)) {
            return Action.LOGIN;
        }

        boolean isFromMenu = isFromMenu(session);
        if (isFromMenu) {
            session.removeAttribute(BaseConstant.SESSION_CONDITION_KEY);
        }
        
        boolean isMenu = isMenu(session);
        
        if (isMenu && !isFromMenu) {
            return Action.LOGIN;
        }

        return invocation.invoke();
    }

    private static boolean isLogin(HttpSession session) {
        if (session == null || session.getAttribute(BaseConstant.SESSION_USER_INFO_KEY) == null) {
            return false;
        }
        return true;
    }

    @SuppressWarnings("unchecked")
    private static boolean isFromMenu(HttpSession session) {
        List<MenuBean> menuInfoList = (List<MenuBean>) session
                .getAttribute(BaseConstant.SESSION_MENU_INFO_KEY);
        if (menuInfoList == null) {
            return false;
        }
        String uri = ServletActionContext.getRequest().getRequestURI();
        for (MenuBean menu : menuInfoList) {
            if (isFromMenu(uri, menu)) {
                return true;
            }
        }

        return false;
    }
    
    private static boolean isFromMenu(String uri, MenuBean menu) {
        if (uri.endsWith(menu.getUrl())) {
            return true;
        }
        
        if (menu.getMenu() == null || menu.getMenu().isEmpty()) {
            return false;
        }
        
        for (MenuBean subMenu : menu.getMenu()) {
            if (uri.endsWith(subMenu.getUrl())) {
                return true;
            }
        }
        return false;
    }

    @SuppressWarnings("unchecked")
    private static boolean isMenu(HttpSession session) {
        List<MenuBean> allMenuInfo = (List<MenuBean>) session
                .getAttribute(BaseConstant.SESSION_ALL_MENU_INFO_KEY);
        String uri = ServletActionContext.getRequest().getRequestURI();
        for (MenuBean menu : allMenuInfo) {
            if (isFromMenu(uri, menu)) {
                return true;
            }
        }
        return false;
    }
}
